from flask import render_template, jsonify, g, redirect, request, current_app, abort

from application import constants, db
from application.models import Category, News, User
from application.utils.common import user_login_data
from application.utils.image_storage import storage
from application.utils.response_code import RET
from . import user_blue

@user_blue.route("/info")
@user_login_data
def user_info():
    """
    用户基本资料页面
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")

    # 用户登录前端实现
    data = {
        "user": user.to_dict() if user else None
    }
    return render_template("users/user.html", data = data)


@user_blue.route("/base_info", methods=["GET", "POST"])
@user_login_data
def base_info():
    """
    基本资料页面逻辑
        1.判断请求方式,如果是GET,那么直接返回页面
        2.如果是POST则代表需要修改基本资料
        3.获取用户数据
        4.校验参数

    :return:
    """
    if request.method == "GET":
        return render_template("users/user_base_info.html", data={"user" : g.user.to_dict()})

    # 修改用户数据
    # 1.取到传入的参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    # 2.校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    if gender not in("MAN", "WOMEN"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 获取用户模型
    user = g.user
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    return jsonify(errno=RET.OK, errmsg="OK")


@user_blue.route("/pic_info", methods=['GET', 'POST'])
@user_login_data
def pic_info():
    """
    用户头像修改
        1.判断请求方式,如果是GET,那么直接返回页面
        2.如果是POST则代表需要修改基本资料
        3.获取用户数据(用户上传的文件)
        4.上传文件到七牛云
    :return:
    """
    user = g.user
    # 1.判断请求方式,如果是GET,那么直接返回页面
    if request.method == "GET":
        return render_template("users/user_pic_info.html", data = {"user" : user.to_dict()})

    # 2.如果是POST则代表需要修改基本资料
    else:
        # 3.获取用户数据(用户上传的文件)
        try:
            avatar_file = request.files.get("avatar").read()
        except Exception as e:
            return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")

#       # 4.上传文件到七牛云
        try:
            key = storage(avatar_file)
        except Exception as e:
            return jsonify(errno=RET.THIRDERR, errmsg="上传文件失败")

        # 5. 上传成功的头像url保存到数据库中
        user.avatar_url = key
        data = {
            "avatar_url" : constants.QINIU_DOMIN_PREFIX + key
        }
        return jsonify(errno=RET.OK, errmsg="上传成功", data = data)

@user_blue.route("/pass_info", methods=['GET', 'POST'])
@user_login_data
def pass_info():
    """
    修改密码
        1.获取参数
        2.校验参数
        3.修改更新密码并返回数据
    :return:
    """
    user = g.user
    if request.method == 'GET':
        return render_template("users/user_pass_info.html")
    else:
        # 1.获取参数
        old_password = request.json.get("old_password")
        new_password = request.json.get("new_password")

        # 2.校验参数
        if not all([old_password, new_password]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        if not user.check_passowrd(old_password):
            return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

        # 3.修改更新密码并返回数据
        user.password = new_password
        return jsonify(errno=RET.OK, errmsg="修改成功")


@user_blue.route("/collection", methods=["GET"])
@user_login_data
def url_collection():
    """
    收藏新闻
        1.获取参数
        2.判断参数
    :return:
    """
    # 1.获取参数
    page = request.args.get("page", 1)

    # 2.校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1


    # 3.查询用户指定页数的新闻
    user = g.user
    news_list = []
    total_page = 1
    current_page = 1
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "current_page" : current_page,
        "total_page" : total_page,
        "collections" : news_dict_li
    }

    return  render_template("users/user_collection.html", data = data)

@user_blue.route("/news_release", methods=["GET", "POST"])
@user_login_data
def news_release():
    """
    新闻发布逻辑
        1.获取参数
        2.校验参数
        3.初始化新闻模型,并设置相关数据
    :return:
    """
    if request.method == 'GET':
        # 加载新闻分类数据
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())

        # 移除最新的分类
        category_dict_li.pop(0)

        data = {
            "categories" : category_dict_li
        }


        return render_template("users/user_news_release.html", data = data)
    else:
        # 1.获取参数
        # 标题
        title = request.form.get("title")
        source = "个人发布"
        # 新闻分类id
        category_id = request.form.get("category_id")
        # 摘要
        digest = request.form.get("digest")
        # 索引图片
        index_image = request.files.get("index_image")
        # 新闻内容
        content = request.form.get("content")


        # 校验参数
        if not all([title, category_id, digest, index_image, content]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
        try:
            category_id = int(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        # 读取图片
        try:
            index_image_data = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        # 将图片上传到七牛云
        try:
            key = storage(index_image_data)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

        # 3.初始化新闻模型,并设置相关数据
        news = News()
        news.title = title
        news.digest = digest
        news.source = source
        news.content = content
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
        news.category_id = category_id
        news.user_id = g.user.id

        # 1代表待审核状态
        news.status = 1

        # 添加数据到数据库
        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
        # 5.返回结果
        return jsonify(errno=RET.OK, errmsg="发布成功,等待审核")


@user_blue.route("/news_list", methods=["GET"])
@user_login_data
def news_list():
    """
    新闻列表
        1.获取参数
        2.校验参数
    :return:
    """
    page = request.args.get("page", 1)
    user = g.user
    current_page = 1
    total_page = 1
    user_news_list = []
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        user_news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in user_news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "news_list" : news_dict_li,
        "current_page": current_page,
        "total_page": total_page,
    }
    return render_template("users/user_news_list.html", data = data)


@user_blue.route("/user_follow")
@user_login_data
def user_follow():
    """
    个人中心:我的关注
    :return:
    """
    # 获取页数
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 取到当前登录用户
    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {
        "users": user_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }

    return render_template('users/user_follow.html', data=data)

@user_blue.route("/other_info")
@user_login_data
def other_info():
    user = g.user

    # 查询其他人的用户信息
    other_id = request.args.get("user_id")

    if not other_id:
        abort(404)

    # 查询指定id的用户信息
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    # 是否关注
    is_followed = False
    # if 当前新闻有作者, 并且 当前登录用户已关注过这个用户
    if other and user:
        # if user 是否关注过 news.user
        if other in user.followed:
            is_followed = True




    data = {
        "user" : user.to_dict() if user else None,
        "other" : other.to_dict(),
        "is_followed" : is_followed
    }
    return render_template("users/other.html", data = data)


@user_blue.route("/other_news_list")
def other_news_list():
    """
    返回指定用户的发布的新闻
    :return:
    """
    other_id = request.args.get("user_id")
    page = request.args.get("page", 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="当前用户不存在")

    try:
        paginate = other.news_list.order_by(News.create_time.desc()).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())

    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)